package com.foamya.minego

import android.annotation.SuppressLint
import android.content.SharedPreferences
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.view.View.OnClickListener
import android.widget.ImageButton
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView

class GameActivity : AppCompatActivity(), OnClickListener {

    // 头部控件
    private lateinit var backBtn: ImageButton // 返回按钮
    private lateinit var resetBtn: ImageButton // 重置按钮
    private lateinit var levelTv: TextView // 关卡
    private lateinit var timeTv: TextView // 时间文字
    private lateinit var wayBtn: ImageButton // 切换游戏方式按钮
    private lateinit var taskTv: TextView // 剩余旗子数量文字
    private lateinit var footTv: TextView // 脚部提示

    private lateinit var recyclerView: RecyclerView // 方块地图控件
    private lateinit var recyclerAdapter: RecyclerAdapter

    // 存储关卡
    private lateinit var preferences: SharedPreferences

    // 时间
    private var minute = 0 // 分钟
    private var second = 0 // 秒
    private var millisecond = 0 // 毫秒

    private var handler = Handler(Looper.getMainLooper()) // 主UI线程

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_game)
        // 私有化
        preferences = getSharedPreferences("level", MODE_PRIVATE)

        // 实例化控件
        instantView()
        // 初始化页面
        initPage()
    }

    @SuppressLint("NotifyDataSetChanged", "SetTextI18n")
    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.mine_top_btn_back -> {
                handler.removeCallbacks(countdown) // 停止倒计时
                finish()
            }

            R.id.mine_top_btn_reset -> {
                handler.removeCallbacks(countdown) // 停止倒计时
                val level = preferences.getInt("level", 0)
                initGame(level) // 初始化游戏
                recyclerAdapter.notifyDataSetChanged()
            }

            R.id.mine_top_btn_way -> {
                replaceWay()
            }
        }
    }


    /**
     * 倒计时器
     */
    private val countdown: Runnable = object : Runnable {
        @SuppressLint("SetTextI18n", "NotifyDataSetChanged")
        override fun run() {

            handler.postDelayed(this, 1) // 变化速度

            if (minute == 0 && second == 0 && millisecond == 0) { // 倒计时结束
                handler.removeCallbacks(this) // 停止倒计时
                BoxUtil.isExpandMap = true // 展开地图
                BoxUtil.isWin = 0 // 游戏结果标记为失败
                recyclerAdapter.notifyDataSetChanged() // 刷新地图
                showResultDialog() // 弹出结果弹窗
            }

            if (minute == 0 && second < 10) {
                timeTv.setTextColor(Color.parseColor("#FFC50909"))
            } else {
                timeTv.setTextColor(Color.parseColor("#FF8A8A8A"))
            }

            if (minute > 0 && second == 0) {
                minute--
                second = 59
            }
            if (second > 0 && millisecond == 0) {
                millisecond = 99
                second--
            }
            if (millisecond > 0) {
                millisecond--
            }

            val minuteStr = if (minute < 10) "0$minute" else minute.toString()
            val secondStr = if (second < 10) "0$second" else second.toString()
            val millisecondStr =
                if (millisecond < 10) "0$millisecond"
                else millisecond.toString()
            timeTv.text = "$minuteStr:$secondStr:$millisecondStr"

        }
    }

    /**
     * 展示结果弹窗
     */
    @SuppressLint("SetTextI18n", "InflateParams", "CommitPrefEdits")
    private fun showResultDialog() {

        val dialog = ResultDialog(this)
        dialog.show()

        val newLevel = BoxUtil.level // 获取缓存的关卡
        val oldLevel = preferences.getInt("level", 0) // 获取保存的关卡
        val edit = preferences.edit()
        if (newLevel != oldLevel) {
            edit.clear()
            edit.putInt("level", newLevel) // 保存新关卡
            edit.apply()
        }

        dialog.setOnBehaviorListener(object : ResultDialog.OnBehaviorListener {
            override fun home() {
                finish()
            }

            @SuppressLint("NotifyDataSetChanged")
            override fun next() {
                initGame(newLevel) // 初始化游戏
                recyclerView.layoutManager = GridLayoutManager(this@GameActivity, BoxUtil.rowSpan)
                recyclerView.adapter = recyclerAdapter
                recyclerAdapter.notifyDataSetChanged() // 刷新页面
            }

            @SuppressLint("NotifyDataSetChanged")
            override fun retry() {
                if (BoxUtil.isWin == 1) { // 成功时默认关卡增加，重玩则恢复关卡
                    edit.clear()
                    edit.putInt("level", oldLevel)
                    edit.apply()
                }
                initGame(oldLevel) // 初始化游戏
                recyclerAdapter.notifyDataSetChanged() // 刷新页面
            }
        })
    }

    /**
     * 实例化控件
     */
    private fun instantView() {
        // 雷区顶部
        backBtn = findViewById(R.id.mine_top_btn_back)
        resetBtn = findViewById(R.id.mine_top_btn_reset)
        levelTv = findViewById(R.id.mine_top_level)
        timeTv = findViewById(R.id.mine_top_tv_time)
        wayBtn = findViewById(R.id.mine_top_btn_way)
        taskTv = findViewById(R.id.mine_top_tv_task)

        backBtn.setOnClickListener(this)
        resetBtn.setOnClickListener(this)
        wayBtn.setOnClickListener(this)

        footTv = findViewById(R.id.mine_foot) // 雷区底部

        // 雷区
        recyclerView = findViewById(R.id.mine_body_recycler)
        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() { // 滑动监听
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

                // 获取当前页面里最后一个子View
                val lastChildView =
                    recyclerView.layoutManager?.getChildAt(recyclerView.layoutManager!!.childCount - 1)
                val lastChildBottom = lastChildView?.bottom // 获取当前view的下坐标
                // 获取当前的position值
                val lastChildPosition = recyclerView.layoutManager?.getPosition(lastChildView!!)

                // 获取组件的下坐标
                val recyclerBottom = recyclerView.bottom - recyclerView.paddingBottom
                // 计算出组件最后一个item的position值
                val recyclerPosition = recyclerView.layoutManager!!.itemCount - 1

                footTv.text =
                    if (recyclerPosition <= 180) // 页面组件未满时
                        ""
                    else if (lastChildBottom == recyclerBottom && lastChildPosition == recyclerPosition)
                        "" // 滑到底部时
                    else "可向下滑动" // 未滑到底部时
            }
        })
    }

    /**
     * 初始化页面
     */
    @SuppressLint("SetTextI18n", "NotifyDataSetChanged")
    private fun initPage() {

        val level = preferences.getInt("level", 0) // 获取关卡

        initGame(level) // 初始化游戏

        // 初始化顶栏游戏方式
        if (BoxUtil.isFlag) wayBtn.setImageResource(R.mipmap.way_flag)
        else wayBtn.setImageResource(R.mipmap.way_shovel)

        recyclerView.layoutManager = GridLayoutManager(this, BoxUtil.rowSpan)
        recyclerAdapter = RecyclerAdapter(this)
        recyclerView.adapter = recyclerAdapter

        recyclerAdapter.setOnEnsureListener(object : RecyclerAdapter.OnBehaviorListener {
            override fun gameStart() {
                // 倒计时开始
                handler.post(countdown)
            }

            override fun useShovel(x: Int, y: Int) {
                when (BoxUtil.isWin) {
                    -1 -> BoxUtil.expandBox(x, y)
                    0 -> gameFail()
                    1 -> gameWin()
                }
            }

            override fun useFlag() {
                when (BoxUtil.isWin) {
                    -1 -> {
                        BoxUtil.lastFlagNum--
                        taskTv.text = BoxUtil.lastFlagNum.toString()
                    }

                    0 -> gameFail()
                    1 -> gameWin()
                }
            }

            override fun cancelFlag() {
                when (BoxUtil.isWin) {
                    -1 -> {
                        BoxUtil.lastFlagNum++
                        taskTv.text = BoxUtil.lastFlagNum.toString()
                    }

                    0 -> gameFail()
                    1 -> gameWin()
                }
            }

            override fun gameWin() {
                handler.removeCallbacks(countdown) // 停止倒计时
                BoxUtil.isWin = 1 // 游戏结果标记为胜利
                showResultDialog() // 弹出结果弹窗
            }

            override fun gameFail() {
                handler.removeCallbacks(countdown) // 停止倒计时
                BoxUtil.isWin = 0 // 游戏结果标记为失败
                showResultDialog() // 弹出结果弹窗
            }
        })
    }

    /**
     * 初始化游戏
     *
     * @param level 关卡
     */
    @SuppressLint("SetTextI18n")
    private fun initGame(level: Int) {
        BoxUtil.initBoxMap(level) // 初始化雷区

        levelTv.text = "第 $level 关"

        // 根据方块数量计算总时间
        minute = (BoxUtil.lastNotMineNum * BoxUtil.hardDegree + level).toInt() / 60
        second = (BoxUtil.lastNotMineNum * BoxUtil.hardDegree + level).toInt() % 60
        millisecond = 0

        // 初始化顶栏时间文字
        timeTv.text = "${if (minute < 10) "0$minute" else minute.toString()}:" +
                "${if (second < 10) "0$second" else second.toString()}:" +
                if (millisecond < 10) "0$millisecond"
                else millisecond.toString()
        if (minute == 0 && second <= 10 && millisecond == 0) {
            timeTv.setTextColor(Color.parseColor("#FFC50909"))
        } else {
            timeTv.setTextColor(Color.parseColor("#FF8A8A8A"))
        }

        // 初始化顶栏剩余旗子数量文字
        taskTv.text = "${BoxUtil.lastFlagNum}"
    }

    /**
     * 点击图标切换铲子或旗子
     */
    private fun replaceWay() {
        if (BoxUtil.isFlag) { // 旗子转铲子
            wayBtn.setImageResource(R.mipmap.way_shovel)
            BoxUtil.isFlag = false
        } else { // 铲子转旗子
            wayBtn.setImageResource(R.mipmap.way_flag)
            BoxUtil.isFlag = true
        }
    }
}